<template>
    <page-container title="职位列表">
        <template #extra>
            <el-input 
                v-model="search" 
                placeholder="请输入关键字" 
                style="width: 150px;height: 30px;margin-left: 100px;" 
                clearable
            />
            <el-button 
                style="margin-left: 20px; background-color: #5defc1; color: white" 
                @click="loadPositions" 
                plain
            >查询</el-button>
           
            <el-button 
                style="margin-left: 20px;"
                type="primary" 
                @click="addPositions"
            >添加职位</el-button>
            <el-button 
                style="margin-left: 20px;"
                type="danger" 
                @click="handleBatchDelete"
               
            >批量删除</el-button>
          
            <div>
    <el-upload
      class="upload-demo"
      :auto-upload="true"
      :show-file-list="false"
      accept=".xls,.xlsx"
      :http-request="customRequest"
      style="margin-left: 20px;"
    >
      <el-button type="warning">导入Excel</el-button>
    </el-upload>
    <div>{{ message }}</div>
  </div>
  <el-button 
                style="margin-left: 20px;"
                type="success" 
                @click="handleExportExcel"
               
            >导出Excel</el-button>
    </template>

        <el-table 
            :data="positions" 
            style="width: 100%" 
            v-loading="tableLoading"
            @selection-change="handleSelectionChange"
        > 
            <el-table-column type="selection" width="45" />
            <el-table-column type="index" label="序号" width="60"/>
            <el-table-column prop="positionName" label="职位名称" width="120">
                <template #default="scope">
                    <el-popover effect="light" width="auto" trigger="contextmenu">
                        <template #reference>
                            <el-tag>{{ scope.row.positionName }}</el-tag>
                        </template>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column prop="positionDescription" label="职位描述" width="200" show-overflow-tooltip/>
            <el-table-column prop="degreeRequirement" label="学历要求" width="100"/>
            <el-table-column prop="workExperience" label="工作经验" width="100"/>
            <el-table-column prop="salary" label="薪资范围" width="100"/>
            <el-table-column prop="departmentName" label="所属部门" width="100"/>
            <el-table-column prop="createTime" label="创建时间" width="200">
                <template #default="{ row }">
                    {{ formatDateTime(row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="200">
                <template #default="{ row }">
                    {{ formatDateTime(row.updateTime) }}
                </template>
            </el-table-column>
            
            <el-table-column label="操作" width="120" >
                <template #default="scope">
                    <el-tooltip content="编辑" placement="top">
                        <el-button 
                            type="primary" 
                            :icon="Edit" 
                            circle
                            size="small"
                            @click="editPosition(scope.row)"
                        />
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                        <el-button 
                            type="danger" 
                            :icon="Delete" 
                            circle
                            size="small"
                            @click="deletePositions(scope.row)"
                        />
                    </el-tooltip>
                </template>
            </el-table-column>

            <template #empty>
                <el-empty description="暂无数据" />
            </template>
      
           
        </el-table>
        <template #pagination>
        <div class="demo-pagination-block">
        <el-pagination
            v-show="total > 0"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
        </template>
        <el-drawer 
            v-model="dialogVisible" 
            title="职位信息" 
            width="50%" 
            direction="rtl"
        >
            <el-form 
                :model="form" 
                label-width="120px" 
                ref="formRef"
            >
                <el-form-item label="职位名称" required>
                    <el-input 
                        v-model="form.positionName"
                        placeholder="请输入职位名称"
                    />
                </el-form-item>
                
                <el-form-item label="学历要求">
                    <el-select 
                        v-model="form.degreeRequirement" 
                        placeholder="请选择学历"
                        clearable
                    >
                        <el-option label="不限" value="不限" />
                        <el-option label="大专" value="大专" />
                        <el-option label="本科" value="本科" />
                        <el-option label="硕士" value="硕士" />
                        <el-option label="博士" value="博士" />
                    </el-select>
                </el-form-item>
                
                <el-form-item label="工作经验">
                    <el-input v-model="form.workExperience" />
                </el-form-item>
                <el-form-item label="薪资范围">
                    <el-input v-model="form.salary" />
                </el-form-item>
                <el-form-item label="所属部门" required>
                    <el-select
                        v-model="form.departmentName"
                        placeholder="请选择部门"
                        @focus="loadDepartments"
                        @change="departmentChange"
                        clearable
                    >
                        <el-option
                            v-for="item in departmentMap"
                            :key="item.departmentId"
                            :label="item.departmentName"
                            :value="item.departmentName"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item label="职位描述">
                    <div class="editor">
                        <quill-editor 
                            ref="editorRef"
                            theme="snow" 
                            v-model:content="form.positionDescription" 
                            content-type="text"
                            @update:content="handleEditorChange"
                        />
                    </div>
                </el-form-item>
                
                <el-form-item>
                    <el-button type="primary" @click="savePosition">保存</el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </page-container>
</template>

<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { Edit, Delete } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ref, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getPositions, addPosition, updatePosition, deletePosition, deleteBatchPositions, importExcel, exportExcel } from '@/api/positions'
import { getDepartments } from '@/api/department'
const departmentMap = ref([])
const dialogVisible = ref(false)
const positions = ref([])
const tableLoading = ref(true)
const search = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedRows = ref([])
const editorRef = ref(null)
const message = ref('');
const form = ref({
    positionName: '',
    positionDescription: '',
    degreeRequirement: '',
    workExperience: '',
    salary: '',
    departmentName: ''
})
const admin=JSON.parse(localStorage.getItem('admin'))
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
   
    console.log(selectedRows.value)
}

const loadDepartments = async () => {
    try {
        const res = await getDepartments()
    
        if (res.code === 200) {
            departmentMap.value = res.data
        } else {
            ElMessage.error('获取部门列表失败')
        }
    } catch (error) {
        ElMessage.error('获取部门列表失败：' + error.message)
    }
}

const departmentChange = (departmentName) => {
    const department = departmentMap.value.find(item => item.departmentName === departmentName)
    if (department) {
        form.value.departmentName = department.departmentName
        form.value.departmentId=department.departmentId
    }
}

const loadPositions = async () => {
    try {
        //tableLoading.value = true
        const res = await getPositions({
            current: currentPage.value,
            size: pageSize.value,
            search: search.value
        })
        console.log(res)
        if (res.code === 200) {
            positions.value = res.data.records
            total.value = res.data.total
        } else {
            ElMessage.error('获取职位列表失败')
        }
    } catch (error) {
        console.error('查询失败：', error)
        ElMessage.error('获取职位列表失败：' + error.message)
    } finally {
        tableLoading.value = false
    }
}

const handleEditorChange = (content) => {
    form.value.positionDescription = content
}

const addPositions = () => {
   if(schema()){
     dialogVisible.value = true
     form.value = {
       positionName: '',
       positionDescription: '',
       degreeRequirement: '',
       workExperience: '',
       salary: '',
       departmentName: ''
     }
   }

}

const editPosition = (row) => {
  if(schema()){
    dialogVisible.value = true
    form.value = {...row}
  }

}

const deletePositions = (row) => {
  if(schema()){
    ElMessageBox.confirm('确定要删除该职位吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const res = await deletePosition(row.positionId)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        await loadPositions()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }).catch(() => {
      ElMessage.info('取消删除')
    })
  }

}

const handleBatchDelete = async () => {
  if(schema()){
    // 获取选中的ID数组
    const ids = selectedRows.value.map(row => row.positionId)
    console.log('要删除的ID：', ids)

    if (ids.length === 0) {
      ElMessage.warning('请选择要删除的职位')
      return
    }

    try {
      await ElMessageBox.confirm('确定要删除选中的职位吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })

      // 直接传递ID数组
      const res = await deleteBatchPositions(ids)

      console.log('批量删除响应：', res)  // 调试用

      if (res.code === 200) {
        ElMessage.success('批量删除成功')
        await loadPositions()
      } else {
        ElMessage.error(res.message || '批量删除失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('批量删除失败：', error)
        ElMessage.error('批量删除失败：' + error.message)
      }
    }
  }

}

const savePosition = async () => {
    if (!form.value.positionName || !form.value.departmentName || 
        !form.value.degreeRequirement || !form.value.workExperience || 
        !form.value.salary) {
        ElMessage.warning('请填写完整信息')
        return
    }

    try {
        const postData = {
            ...form.value,
            departmentId:form.value.departmentId,
            positionName: form.value.positionName.trim(),
            degreeRequirement: form.value.degreeRequirement.trim(),
            workExperience: form.value.workExperience.trim(),
            salary: form.value.salary.trim(),
            departmentName: form.value.departmentName.trim()
        }

        const res = form.value.positionId
            ? await updatePosition(postData)
            : await addPosition(postData)

        if (res.code === 200) {
            ElMessage.success(form.value.positionId ? '更新成功' : '添加成功')
            dialogVisible.value = false
            editorRef.value.setText('')
            await loadPositions()
        } else {
            ElMessage.error(res.message || (form.value.positionId ? '更新失败' : '添加失败'))
        }
    } catch (error) {
        console.error(form.value.positionId ? '更新失败' : '添加失败', error)
        ElMessage.error((form.value.positionId ? '更新' : '添加') + '失败：' + 
            (error.response?.data?.message || error.message))
    }
}

const formatDateTime = (dateStr) => {
    if (!dateStr) return '--'
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    })
}
const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    loadPositions()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    loadPositions()
}


    const customRequest = async (options) => {
        if(schema()){
          try {
            const formData = new FormData()
            formData.append('file', options.file)

            const res = await importExcel(formData)  // 使用封装的API方法
            console.log('上传响应：', res)

            if (res.code === 200) {
              ElMessage.success('导入成功')
              await loadPositions()  // 刷新列表
            } else {
              ElMessage.error(res.message || '导入失败')
            }
          } catch (error) {
            console.error('导入失败：', error)
            ElMessage.error('导入失败：' + error.message)
          }
        }

    }

const handleExportExcel = async () => {
    if(schema()){
      try {
        const res = await exportExcel()

        // 从响应头中获取文件名
        const fileName = '职位列表.xlsx'

        // 创建 blob 对象，指定正确的 MIME 类型
        const blob = new Blob([res], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })

        // 创建下载链接
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()

        // 清理
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)

        ElMessage.success('导出成功')
      } catch (error) {
        console.error('导出失败：', error)
        ElMessage.error('导出失败：' + error.message)
      }
    }

}
const schema = () => {
  if (admin === null) {
    ElMessage.warning('您没有权限进行此操作');
    return false;
  }
  // 其他权限检查逻辑
  if (admin.role === 'super_admin' || admin.role === 'admin') {
    console.log(admin.role);
    return true;
  } else {
    ElMessage.warning('您没有权限进行此操作');
    return false;
  }
}
onMounted(() => {
    setTimeout(() => {
        loadPositions()
        loadDepartments()
    }, 1000)
})
</script>

<style scoped>

.editor {
    width: 100%;
    margin-bottom: 20px;
}

:deep(.ql-editor) {
    min-height: 200px;
}

.demo-pagination-block {
    margin-top: 20px;
    display: flex;
    justify-content: flex-start;
}

/* .upload-demo {
    margin-bottom: 20px;
} */



</style>


